<template>
  <div class="home">
    <ul >
      <li v-for="item of msgList" :key="item.id" >
      <p>
        <span>{{item.user}}</span>
        <span>{{new Date(item.dateTime) }}</span>
        <p>{{item.msg}}</p>
      </p>
      </li>
    </ul>




<input type="text" placeholder="请输入消息" v-model="msg">
<button @click = 'handleSendBtnClick'>发送</button>
   </div>
</template>

<script>

const ws = new WebSocket('ws://localhost:8000')

export default {
  name: 'Home',
  data() {
    return {
      msg: '',
      username: '',
      msgList: []
    }
  },
  mounted() {
    this.username = localStorage.getItem('username');
    if (!this.username) {
      this.$router.push('/login')
      return
    }

    ws.addEventListener('open',this.handleWsOpen.bind(this),false)
    ws.addEventListener('close', this.handleWsClose.bind(this), false)
    ws.addEventListener('error',this.handleWsError.bind(this),false)
    ws.addEventListener('message',this.handleWsMessage.bind(this),false)

  },
  methods: {
    handleSendBtnClick() {
      // console.log(this.msg.trim());
      const msg = this.msg.trim();
      if (!msg) {
        return
      }
      ws.send(JSON.stringify({
        id: new Date().getTime(),
        user: this.username,
        dateTime: new Date().getTime(),
        msg
      }));

      
      this.msg = ''
    }, handleWsOpen(e) {
      console.log('FE:WsOpen',e);
    }, handleWsClose(e) {
      console.log('FE:WsClose',e);
    }, handleWsError(e) {
      console.log('FE:WsError',e);
    }, handleWsMessage(e) {
      console.log('FE:WsMessage', e);
     let  data = JSON.parse(e.data)
      console.log(data)
      this.msgList.push(data);
    }

  },

}
</script>
